/**
 * 本地存储工具类
 * 提供统一的本地存储操作接口
 */

// 存储前缀，避免键名冲突
const STORAGE_PREFIX = 'rag_ai_'

/**
 * 获取完整的存储键名
 * @param {string} key 原始键名
 * @returns {string} 完整的存储键名
 */
const getFullKey = (key) => {
  return STORAGE_PREFIX + key
}

/**
 * 设置本地存储
 * @param {string} key 键名
 * @param {any} value 值
 * @param {number} expire 过期时间（毫秒），可选
 */
export const setStorage = (key, value, expire = null) => {
  try {
    const fullKey = getFullKey(key)
    const data = {
      value,
      timestamp: Date.now()
    }
    
    if (expire) {
      data.expire = expire
    }
    
    localStorage.setItem(fullKey, JSON.stringify(data))
  } catch (error) {
    console.error('设置本地存储失败:', error)
  }
}

/**
 * 获取本地存储
 * @param {string} key 键名
 * @param {any} defaultValue 默认值
 * @returns {any} 存储的值或默认值
 */
export const getStorage = (key, defaultValue = null) => {
  try {
    const fullKey = getFullKey(key)
    const data = localStorage.getItem(fullKey)
    
    if (!data) {
      return defaultValue
    }
    
    const parsedData = JSON.parse(data)
    
    // 检查是否过期
    if (parsedData.expire) {
      const now = Date.now()
      const expireTime = parsedData.timestamp + parsedData.expire
      
      if (now > expireTime) {
        // 数据已过期，删除并返回默认值
        removeStorage(key)
        return defaultValue
      }
    }
    
    return parsedData.value
  } catch (error) {
    console.error('获取本地存储失败:', error)
    return defaultValue
  }
}

/**
 * 删除本地存储
 * @param {string} key 键名
 */
export const removeStorage = (key) => {
  try {
    const fullKey = getFullKey(key)
    localStorage.removeItem(fullKey)
  } catch (error) {
    console.error('删除本地存储失败:', error)
  }
}

/**
 * 清空所有本地存储
 */
export const clearStorage = () => {
  try {
    const keys = Object.keys(localStorage)
    keys.forEach(key => {
      if (key.startsWith(STORAGE_PREFIX)) {
        localStorage.removeItem(key)
      }
    })
  } catch (error) {
    console.error('清空本地存储失败:', error)
  }
}

/**
 * 检查本地存储是否存在
 * @param {string} key 键名
 * @returns {boolean} 是否存在
 */
export const hasStorage = (key) => {
  try {
    const fullKey = getFullKey(key)
    return localStorage.getItem(fullKey) !== null
  } catch (error) {
    console.error('检查本地存储失败:', error)
    return false
  }
}

/**
 * 获取所有存储的键名
 * @returns {string[]} 键名数组
 */
export const getStorageKeys = () => {
  try {
    const keys = Object.keys(localStorage)
    return keys
      .filter(key => key.startsWith(STORAGE_PREFIX))
      .map(key => key.replace(STORAGE_PREFIX, ''))
  } catch (error) {
    console.error('获取存储键名失败:', error)
    return []
  }
}

/**
 * 获取存储大小（字节）
 * @returns {number} 存储大小
 */
export const getStorageSize = () => {
  try {
    let size = 0
    const keys = Object.keys(localStorage)
    
    keys.forEach(key => {
      if (key.startsWith(STORAGE_PREFIX)) {
        size += localStorage.getItem(key).length
      }
    })
    
    return size
  } catch (error) {
    console.error('获取存储大小失败:', error)
    return 0
  }
}

/**
 * 设置会话存储
 * @param {string} key 键名
 * @param {any} value 值
 */
export const setSessionStorage = (key, value) => {
  try {
    const fullKey = getFullKey(key)
    sessionStorage.setItem(fullKey, JSON.stringify(value))
  } catch (error) {
    console.error('设置会话存储失败:', error)
  }
}

/**
 * 获取会话存储
 * @param {string} key 键名
 * @param {any} defaultValue 默认值
 * @returns {any} 存储的值或默认值
 */
export const getSessionStorage = (key, defaultValue = null) => {
  try {
    const fullKey = getFullKey(key)
    const data = sessionStorage.getItem(fullKey)
    
    if (!data) {
      return defaultValue
    }
    
    return JSON.parse(data)
  } catch (error) {
    console.error('获取会话存储失败:', error)
    return defaultValue
  }
}

/**
 * 删除会话存储
 * @param {string} key 键名
 */
export const removeSessionStorage = (key) => {
  try {
    const fullKey = getFullKey(key)
    sessionStorage.removeItem(fullKey)
  } catch (error) {
    console.error('删除会话存储失败:', error)
  }
}

/**
 * 清空所有会话存储
 */
export const clearSessionStorage = () => {
  try {
    const keys = Object.keys(sessionStorage)
    keys.forEach(key => {
      if (key.startsWith(STORAGE_PREFIX)) {
        sessionStorage.removeItem(key)
      }
    })
  } catch (error) {
    console.error('清空会话存储失败:', error)
  }
}

/**
 * 检查会话存储是否存在
 * @param {string} key 键名
 * @returns {boolean} 是否存在
 */
export const hasSessionStorage = (key) => {
  try {
    const fullKey = getFullKey(key)
    return sessionStorage.getItem(fullKey) !== null
  } catch (error) {
    console.error('检查会话存储失败:', error)
    return false
  }
}

// 用户相关存储键名常量
export const USER_STORAGE_KEYS = {
  TOKEN: 'user_token',
  REFRESH_TOKEN: 'user_refresh_token',
  USER_INFO: 'user_info',
  REMEMBER_ME: 'remember_me',
  REMEMBERED_USERNAME: 'remembered_username',
  REMEMBERED_PASSWORD: 'remembered_password',
  LOGIN_HISTORY: 'login_history',
  THEME: 'user_theme',
  LANGUAGE: 'user_language',
  SETTINGS: 'user_settings',
  // 密码重置验证相关
  PASSWORD_RESET_VERIFICATION: 'password_reset_verification'
}

// 应用相关存储键名常量
export const APP_STORAGE_KEYS = {
  SIDEBAR_COLLAPSED: 'sidebar_collapsed',
  TABLE_PAGE_SIZE: 'table_page_size',
  SEARCH_HISTORY: 'search_history',
  FAVORITES: 'favorites',
  RECENT_FILES: 'recent_files',
  NOTIFICATIONS: 'notifications'
}

/**
 * 用户存储工具函数
 */
export const userStorage = {
  // Token相关
  setToken: (token) => setStorage(USER_STORAGE_KEYS.TOKEN, token),
  getToken: () => getStorage(USER_STORAGE_KEYS.TOKEN),
  removeToken: () => removeStorage(USER_STORAGE_KEYS.TOKEN),
  
  // Refresh Token相关
  setRefreshToken: (token) => setStorage(USER_STORAGE_KEYS.REFRESH_TOKEN, token),
  getRefreshToken: () => getStorage(USER_STORAGE_KEYS.REFRESH_TOKEN),
  removeRefreshToken: () => removeStorage(USER_STORAGE_KEYS.REFRESH_TOKEN),
  
  // 用户信息相关
  setUserInfo: (userInfo) => setStorage(USER_STORAGE_KEYS.USER_INFO, userInfo),
  getUserInfo: () => getStorage(USER_STORAGE_KEYS.USER_INFO),
  removeUserInfo: () => removeStorage(USER_STORAGE_KEYS.USER_INFO),
  
  // 记住我相关
  setRememberMe: (value) => setStorage(USER_STORAGE_KEYS.REMEMBER_ME, value),
  getRememberMe: () => getStorage(USER_STORAGE_KEYS.REMEMBER_ME, false),
  removeRememberMe: () => removeStorage(USER_STORAGE_KEYS.REMEMBER_ME),
  
  // 记住的用户名密码
  setRememberedUsername: (username) => setStorage(USER_STORAGE_KEYS.REMEMBERED_USERNAME, username),
  getRememberedUsername: () => getStorage(USER_STORAGE_KEYS.REMEMBERED_USERNAME),
  removeRememberedUsername: () => removeStorage(USER_STORAGE_KEYS.REMEMBERED_USERNAME),
  
  setRememberedPassword: (password) => setStorage(USER_STORAGE_KEYS.REMEMBERED_PASSWORD, password),
  getRememberedPassword: () => getStorage(USER_STORAGE_KEYS.REMEMBERED_PASSWORD),
  removeRememberedPassword: () => removeStorage(USER_STORAGE_KEYS.REMEMBERED_PASSWORD),
  
  // 登录历史
  setLoginHistory: (history) => setStorage(USER_STORAGE_KEYS.LOGIN_HISTORY, history),
  getLoginHistory: () => getStorage(USER_STORAGE_KEYS.LOGIN_HISTORY, []),
  removeLoginHistory: () => removeStorage(USER_STORAGE_KEYS.LOGIN_HISTORY),
  
  // 主题设置
  setTheme: (theme) => setStorage(USER_STORAGE_KEYS.THEME, theme),
  getTheme: () => getStorage(USER_STORAGE_KEYS.THEME, 'light'),
  removeTheme: () => removeStorage(USER_STORAGE_KEYS.THEME),
  
  // 语言设置
  setLanguage: (language) => setStorage(USER_STORAGE_KEYS.LANGUAGE, language),
  getLanguage: () => getStorage(USER_STORAGE_KEYS.LANGUAGE, 'zh-CN'),
  removeLanguage: () => removeStorage(USER_STORAGE_KEYS.LANGUAGE),
  
  // 用户设置
  setSettings: (settings) => setStorage(USER_STORAGE_KEYS.SETTINGS, settings),
  getSettings: () => getStorage(USER_STORAGE_KEYS.SETTINGS, {}),
  removeSettings: () => removeStorage(USER_STORAGE_KEYS.SETTINGS),
  
  // 密码重置验证相关
  setPasswordResetVerification: (verificationData) => {
    // 设置30分钟过期时间
    const expireTime = 30 * 60 * 1000 // 30分钟
    setStorage(USER_STORAGE_KEYS.PASSWORD_RESET_VERIFICATION, verificationData, expireTime)
  },
  getPasswordResetVerification: () => getStorage(USER_STORAGE_KEYS.PASSWORD_RESET_VERIFICATION),
  removePasswordResetVerification: () => removeStorage(USER_STORAGE_KEYS.PASSWORD_RESET_VERIFICATION),
  hasPasswordResetVerification: () => hasStorage(USER_STORAGE_KEYS.PASSWORD_RESET_VERIFICATION),
  
  // 清除所有用户数据
  clearAll: () => {
    Object.values(USER_STORAGE_KEYS).forEach(key => removeStorage(key))
  }
}

/**
 * 应用存储工具函数
 */
export const appStorage = {
  // 侧边栏状态
  setSidebarCollapsed: (collapsed) => setStorage(APP_STORAGE_KEYS.SIDEBAR_COLLAPSED, collapsed),
  getSidebarCollapsed: () => getStorage(APP_STORAGE_KEYS.SIDEBAR_COLLAPSED, false),
  removeSidebarCollapsed: () => removeStorage(APP_STORAGE_KEYS.SIDEBAR_COLLAPSED),
  
  // 表格分页大小
  setTablePageSize: (size) => setStorage(APP_STORAGE_KEYS.TABLE_PAGE_SIZE, size),
  getTablePageSize: () => getStorage(APP_STORAGE_KEYS.TABLE_PAGE_SIZE, 10),
  removeTablePageSize: () => removeStorage(APP_STORAGE_KEYS.TABLE_PAGE_SIZE),
  
  // 搜索历史
  setSearchHistory: (history) => setStorage(APP_STORAGE_KEYS.SEARCH_HISTORY, history),
  getSearchHistory: () => getStorage(APP_STORAGE_KEYS.SEARCH_HISTORY, []),
  removeSearchHistory: () => removeStorage(APP_STORAGE_KEYS.SEARCH_HISTORY),
  
  // 最近文件
  setRecentFiles: (files) => setStorage(APP_STORAGE_KEYS.RECENT_FILES, files),
  getRecentFiles: () => getStorage(APP_STORAGE_KEYS.RECENT_FILES, []),
  removeRecentFiles: () => removeStorage(APP_STORAGE_KEYS.RECENT_FILES),
  
  // 清除所有应用数据
  clearAll: () => {
    Object.values(APP_STORAGE_KEYS).forEach(key => removeStorage(key))
  }
}

/**
 * 存储管理器
 */
export class StorageManager {
  constructor(prefix = '') {
    this.prefix = prefix
  }
  
  /**
   * 设置存储
   * @param {string} key 键名
   * @param {any} value 值
   * @param {number} expire 过期时间（毫秒）
   */
  set(key, value, expire = null) {
    const fullKey = this.prefix ? `${this.prefix}_${key}` : key
    setStorage(fullKey, value, expire)
  }
  
  /**
   * 获取存储
   * @param {string} key 键名
   * @param {any} defaultValue 默认值
   * @returns {any} 存储的值
   */
  get(key, defaultValue = null) {
    const fullKey = this.prefix ? `${this.prefix}_${key}` : key
    return getStorage(fullKey, defaultValue)
  }
  
  /**
   * 删除存储
   * @param {string} key 键名
   */
  remove(key) {
    const fullKey = this.prefix ? `${this.prefix}_${key}` : key
    removeStorage(fullKey)
  }
  
  /**
   * 检查是否存在
   * @param {string} key 键名
   * @returns {boolean} 是否存在
   */
  has(key) {
    const fullKey = this.prefix ? `${this.prefix}_${key}` : key
    return hasStorage(fullKey)
  }
  
  /**
   * 清空所有相关存储
   */
  clear() {
    const keys = getStorageKeys()
    keys.forEach(key => {
      if (this.prefix && key.startsWith(this.prefix)) {
        removeStorage(key)
      }
    })
  }
}

// 导出默认的存储管理器实例
export default new StorageManager()
